﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;

namespace BuildingForm.PersonInfo
{
    public partial class AttendanceStatistics : Form
    {
        public AttendanceStatistics()
        {
            InitializeComponent();
            Init();
            bind();
        }
        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            //班组
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            DataRow dr3 = dt.NewRow();
            dr3["bzid"] = 0;
            dr3["bzmc"] = "全部";
            dt.Rows.InsertAt(dr3, 0);
            this.cboTeam.DisplayMember = "bzmc";
            this.cboTeam.ValueMember = "bzid";
            this.cboTeam.DataSource = dt;
            //分包
            Maticsoft.DAL.Fenb_Info fenb = new Fenb_Info();
            DataTable dt2 = fenb.GetList("").Tables[0];
            DataRow dr=dt2.NewRow ();
            dr["fbid"]=0;
            dr["fbmc"]="全部";
            dt2.Rows.InsertAt (dr,0);
            this.cboPake.DisplayMember = "fbmc";
            this.cboPake.ValueMember = "fbid";
            this.cboPake.DataSource = dt2;
            //考勤点
            Maticsoft.DAL.Jsd_Info jsd = new Jsd_Info();
            DataTable dt3 = jsd.GetList("").Tables[0];
            DataRow dr2 = dt3.NewRow();
            dr2["jsdbh"] = 0;
            dr2["jsdm"] = "全部";
            dt3.Rows.InsertAt(dr2, 0);
            this.cbokq.DisplayMember = "jsdm";
            this.cbokq.ValueMember = "jsdbh";
            this.cbokq.DataSource = dt3;
            //时间
            this.picBegin.Value = DateTime.Now.AddDays(-7);
            this.picEnd.Value = DateTime.Now;
        }
        decimal totalHours;
        private List<TotalWorkTime> bind()
        {
            totalHours = 0;
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            sql = " 1=1 ";
            DateTime beginT = Convert.ToDateTime(picBegin.Value);
            DateTime endT = Convert.ToDateTime(picEnd.Value);
            if (beginT > endT)
            {
                MessageBox.Show("开始时间不能大于结束时间！"); return new List<TotalWorkTime>();
            }
            sql += " and CONVERT(varchar(10),a.kqsj,120)<='" + endT.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(10),a.kqsj,120)>='" + beginT.ToString("yyyy-MM-dd") + "'";
            string team = this.cboTeam.SelectedValue.ToString();
            string pake = this.cboPake.SelectedValue.ToString();
            string kq = this.cbokq.Text.ToString();
            if (team != "0")
            {
                sql += " and c.bzid='" + team + "'";
            }
            if (pake != "0")
            {
                sql += " and f.fbid='" + pake + "'";
            }
            if (kq != "全部")
            {
                sql += " and a.jsdm='" + kq + "'";
            }
            sql += " order by sfzh,kqsj ";
            DataTable dt = info.GetListByAttendanceStatistics(sql).Tables[0];
            List<WorkTime> list = new List<WorkTime>();
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            WorkTime arg = new WorkTime();
            int num = 1;
            decimal worktime = 0;
            //true进 false出
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                string dksj_1 = dr["dksj"].ToString();
                //if (sfzh_1 != "0566805022") continue;
                if (sfzh_b.Equals(sfzh_1) && dksj_b.Equals(dksj_1))
                {
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        if (endTime == DateTime.MinValue && beginTime != DateTime.MinValue)
                        {
                            endTime = Convert.ToDateTime(dr["kqsj"]);
                            TimeSpan ts = endTime - beginTime;
                            decimal di = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }

                }
                else
                {
                    if (i != 0)
                    {
                        //工时大于0的才记录,不能用worktime，几秒时就是0
                        decimal gs = Math.Round(worktime / 3600, 2);
                        if (gs > 0)
                        {
                            arg.gs = Math.Round(worktime / 3600, 2);
                            worktime = 0;
                            list.Add(arg);
                            num++;
                        }
                    }
                    //防止下一天或一个人的再次
                    beginTime = DateTime.MinValue;
                    endTime = DateTime.MinValue;
                    bool isEnter = Convert.ToBoolean(dr["jczt"]);
                    //进
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }

                    sfzh_b = sfzh_1;
                    dksj_b = dksj_1;
                    WorkTime w = new WorkTime();
                    w.xh = num;
                    w.xm = dr["xm"].ToString();
                    w.gh = dr["gh"].ToString();
                    w.sfzh = dr["sfzh"].ToString();
                    w.bz = dr["bzmc"].ToString();
                    w.gz = dr["gz"].ToString();
                    w.xb = dr["xb"].ToString();
                    w.rq = Convert.ToDateTime(dksj_b);
                    arg = w;
                }
            }
            List<TotalWorkTime> lists = new List<TotalWorkTime>();
            string sfzh = string.Empty;
            int j=0;
            TotalWorkTime twt = new TotalWorkTime();
            foreach (var l in list)
            {
                totalHours += l.gs;
                if (sfzh != l.sfzh)
                {
                    TotalWorkTime twtn = new TotalWorkTime();
                    twtn = twt;
                    twt = new TotalWorkTime();
                    if (!string.IsNullOrEmpty (twtn.sfzh))
                    {
                        lists.Add(twtn);
                    }
                    j++;
                    twt.xh = j;
                    twt.gh = l.gh;
                    twt.bz = l.bz;
                    twt.gz = l.gz;
                    twt.sfzh = l.sfzh;
                    twt.xm = l.xm;
                    twt.xb = l.xb;
                    sfzh = l.sfzh;
                }
                twt.wt += l.gs;
            }
            if (!string.IsNullOrEmpty(twt.sfzh))
            {
                lists.Add(twt);
            }
            lists.Sort(Sort);
            for (int i = 0; i < lists.Count; i++)
            {
                lists[i].xh = (i + 1);
            }
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = lists;
            return lists;
        }

       
        private void button1_Click(object sender, EventArgs e)
        {
            bind();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                List<TotalWorkTime> list = bind();
                if (list.Count == 0)
                {
                    MessageBox.Show("没有数据！"); return;
                }
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "考勤统计" + DateTime.Now.ToString("yyyyMMdd");
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string team = this.cboTeam.Text.ToString().Trim();
                    string fileName = saveFileDialog1.FileName;
                    DateTime dt1 = picBegin.Value;
                    DateTime dt2 = picEnd.Value;
                    string title = dt1.ToString("yyyy年M月d日") + "---" + dt2.ToString("yyyy年M月d日");
                    string[] oldCols = new string[] { "xh", "xm", "sfzh","xb", "gh", "bz", "gz", "wt" };
                    string[] newCols = new string[] { "序号", "姓名", "身份证号","性别", "工号", "班组", "工种", "工时（小时）" };
                    DataTable dt = Common.ConvertHelper.ToDataSet(list).Tables[0];
                    ExcelHelper.ExportByAttendanceStatistics(dt, "考勤统计", fileName, "Sheet1", oldCols, newCols, title, dt.Rows.Count.ToString(), totalHours.ToString(), team);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }

        private static int Sort(TotalWorkTime t1, TotalWorkTime t2)
        {
            if (t1 != null & t2 != null)
            {
                if (t1.bz.CompareTo(t2.bz) > 0)
                {
                    return 1;
                }
                else if (t1.bz.CompareTo(t2.bz) < 0)
                {
                    return -1;
                }
                else
                {
                    return 0;
                }
            }
            return 0;
        }
    }
    public class TotalWorkTime
    {
        public int xh { get; set; }
        public string xm { get; set; }
        public string sfzh { get; set; }
        public string gh { get; set; }
        public string bz { get; set; }
        public string xb { get; set; }
        public string gz { get; set; }
        public decimal wt { get; set; }
    }
}
